#!/usr/bin/env python2.7

# bender.py

import os, sys
#import re
#from datetime import datetime, timedelta
#from dateutil.parser import parse
import numpy as np
import matplotlib
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4']='PySide'
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

#from mpl_toolkits.basemap import Basemap
#from matplotlib import mlab
#from netCDF4 import Dataset
from PySide.QtCore import *
from PySide.QtGui import *
from ui_averager import *
from metlib.kits import Null, Setter, Limiter

class Averager(QWidget, Ui_AveragerWidget, Setter):
    def __init__(self, parent=None):
        super(Averager, self).__init__(parent)
        self.setupUi(self)
        self.aver_min_Label.setNum(self.aver_min)

    def decloud(self, lidard):
        if 'cbi' in lidard:
            if self.strict_decloud:
                if 'cbi_strict' in lidard:
                    cbi = lidard['cbi_strict']
                else:
                    cbi1 = lidard['cbi']
                    cbi1[cbi1 < 0] = lidard.dims['BIN'] -1 + self.n_down
                    LI = Limiter(0, len(cbi1)-1)
                    cbi = np.zeros_like(cbi1) - 1
                    for i in range(len(cbi)):
                        cbi[i] = np.min(cbi1[LI[i-self.n_spread:i+self.n_spread+1]])
                    cbi -= self.n_down
                    cbi[cbi<0] = 0
            else:
                cbi = lidard['cbi']
            cbi[cbi < 0] = lidard.dims['BIN'] - 1
            if self.on:
                for ti in range(len(cbi)):
                    lidard['data'][ti, :, cbi[ti]:] = np.nan
        else:
            cbi = None
        return cbi

    def average(self, lidard):
        if self.on and self.aver_min > 0:
            lidard.time_average(self.aver_min)

    @property
    def aver_min(self):
        return int(self.aver_min_Slider.value())

    @aver_min.setter
    def aver_min(self, value):
        self.aver_min_Slider.setValue(value)
    
    @property
    def on(self):
        return self.checkBox.isChecked()

    @on.setter
    def on(self, value):
        state = Qt.Checked if value else Qt.Unchecked
        self.checkBox.setCheckState(state)

    @property
    def strict_decloud(self):
        return self.strict_decloud_checkBox.isChecked()

    @strict_decloud.setter
    def strict_decloud(self, value):
        state = Qt.Checked if value else Qt.Unchecked
        self.strict_decloud_checkBox.setCheckState(state)

    @property
    def n_down(self):
        return self.down_spinBox.value()

    @n_down.setter
    def n_down(self, value):
        self.down_spinBox.setValue(value)

    @property
    def n_spread(self):
        return self.spread_spinBox.value()

    @n_spread.setter
    def n_spread(self, value):
        self.spread_spinBox.setValue(value)

if __name__ == '__main__':
    pass
